package org.tokaf.rater;

import org.tokaf.TopKElement;
import org.tokaf.datasearcher.DataSearcher;

/**
 * <p>WeightAverage computes rating as x*wx+y*wy+../wx+wy+... It is weighed average. </p>
 * <p>Copyright (c) 2006</p>
 * @author Alan Eckhardt
 * @version 1.0
 */
public class WeightAverage extends WeightRater {

	public WeightAverage(String fields[], double values[]) {
		super(fields, values);
	}

	public WeightAverage() {
		super();
	}

	public double getDerivation(int index, DataSearcher data[], TopKElement el) {
		if (values != null && values.length > index)
			return values[index];
		return -1;
	}

	public double getDerivation(int index, DataSearcher data[], Object[] datas) {
		if (values != null && values.length > index)
			return values[index];
		return -1;
	}

	public double getWeight(int i) {
		if (values != null && values.length > i)
			return values[i];
		return -1;
	}

	public double getRating(TopKElement el, DataSearcher data[], double optional) {
		double res = 0;
		double divider = 0;
		for (int i = 0; i < el.getLength(); i++) {
			divider += values[i];
			if (el.isNull(i))
				res += optional * values[i];
			else
				res += el.getRating(i) * values[i];
		}
		if (divider != 0)
			return res / divider;
		else
			return 0;
	}

	public double getRating(TopKElement el, DataSearcher data[],
			TopKElement threshold) {
		double res = 0;
		double divider = 0;
		for (int i = 0; i < el.getLength(); i++) {
			divider += values[i];
			if (el.isNull(i))
				res += threshold.getRating(i) * values[i];
			else
				res += el.getRating(i) * values[i];
		}
		if (divider != 0)
			return res / divider;
		else
			return 0;
	}

}
